const express = require('express')
const path = require('path');
const bodyParser = require('body-parser')
const md5 = require('md5');
const cookieParser = require('cookie-parser')

const mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1/test5');

const NewsModel = mongoose.model('News', {title: String, viewCount: Number}, 'news');
const AdminModel = mongoose.model('Admin', {username: String, password: String}, 'admins');

const app = express()
const port = 3000

app.use(cookieParser())

app.use(bodyParser.urlencoded({extended: false}))
app.use(bodyParser.json())

app.use(express.static('public'))


app.engine('html', require('express-art-template'));
app.set('view options', {
    debug: process.env.NODE_ENV !== 'production'
});
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');


app.get('/admin/login', (req, res) => {
    console.log(req.cookies, 'cookie');
    res.render('admin/login');
})

app.post('/admin/login', async (req, res) => {
    let username = req.body.username;
    let password = req.body.password;

    // 拿用户提交的用户名和密码，和系统里面的用户名和密码做比较，
    // 如果一致则代表登录成功
    // 注意: 系统里面的第一个用户名和密码，一般都是系统初始化的
    // 系统的自带的，一般我们也叫做超级管理员
    let info = await AdminModel.findOne({username: username});
    if (info) {
        // 判断一下密码是否正确 数据库存储的用户的密码一般都是加密，我们需要在判断的时候，对用户输入的密码加密和数据库的比较
        if (md5(password) != info.password) {
            res.redirect('/admin/login');
        } else {
            // 还要记录一下用户登录的标识，以便在其他页面可以共享登录的状态
            // http协议是无状态 cookie
            // https://blog.csdn.net/rowlet/article/details/119876292
            res.cookie("isLogin", 1);
            res.cookie("username", username);

            // 登录成功 前往首页
            res.redirect('/admin/dashboard');
        }
    } else {
        res.redirect('/admin/login');
    }

})

app.get('/admin/logout', (req, res) => {
    // 清除一下登录的标识
    res.cookie("isLogin", 0);
    res.cookie("username", '');

    res.render('admin/login');
})


app.get('/admin/dashboard', (req, res) => {
    let isLogin = req.cookies.isLogin;
    if (isLogin == 0) {
        res.redirect('/admin/login');
        return;
    }

    let username = req.cookies.username;
    res.render('admin/dashboard', {username: username});
})


app.get('/admin/welcome', (req, res) => {
    let isLogin = req.cookies.isLogin;
    if (isLogin == 0) {
        res.redirect('/admin/login');
        return;
    }

    res.render('admin/welcome');
})

// TODO 自行实现编辑和删除功能
app.get('/admin/news/edit', async (req, res) => {
    console.log(req.query);
    let id = req.query.id;

    res.send('edit');
})

app.get('/admin/news/del', async (req, res) => {
    console.log(req.query);
    let id = req.query.id;

    res.send('del');
})


app.get('/admin/news/list', async (req, res) => {
    let isLogin = req.cookies.isLogin;
    if (isLogin == 0) {
        res.redirect('/admin/login');
        return;
    }

    let newsList = await NewsModel.find();

    res.render('admin/news/list', {newsList: newsList});
})

app.get('/admin/news/add', (req, res) => {
    let isLogin = req.cookies.isLogin;
    if (isLogin == 0) {
        res.redirect('/admin/login');
        return;
    }

    res.render('admin/news/add');
})

app.post('/admin/news/store', async (req, res) => {
    let isLogin = req.cookies.isLogin;
    if (isLogin == 0) {
        res.redirect('/admin/login');
        return;
    }

    // 得到post 数据 https://www.expressjs.com.cn/resources/middleware/body-parser.html
    console.log(req.body);
    let title = req.body.title;
    let viewCount = req.body.viewCount;

    const model = new NewsModel({title: title, viewCount: parseInt(viewCount)});
    let data = await model.save();
    // mongoosejs
    // res.send('post ok');
    res.redirect('/admin/news/list');

})

/*
* 新闻列表接口
* */
app.get('/api/v1/news/list', async (req, res) => {
    let newsList = await NewsModel.find();
    res.json({
        status: 'success',
        code: 0,
        msg: '新闻列表获取成功',
        data: {
            list: newsList
        }
    })
})
/*
* 接口文档一般我们做好接口，还需要提供一份接口文档供前端使用
* apipost
* */

app.listen(port, () => {
    console.log(`app listening on port ${port}`)
})
